package com.castudio.Controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.castudio.Common.QueryPageParam;
import com.castudio.Common.RespPageEntity;
import com.castudio.Entity.Dto.Code;
import com.castudio.Entity.User;
import com.castudio.Filter.R;
import com.castudio.Filter.Result;
import com.castudio.Mapper.UserMapper;
import com.castudio.Service.UserService;
import com.castudio.Util.ApiResult;
import com.castudio.Util.TimeUtils;
//import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 小陈同学
 * @since 2022-12-14
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private UserService userService;

   /* @Resource
    private COSConfig COSConfig;*/
    @Resource
    private UserMapper userMapper;

   @GetMapping("/all")
    public List<User> listAll(){

       return userService.list();

   }

   /*新增*/
    @PostMapping("/add")
    public Result add(@RequestBody User user){

        return userService.save(user)?Result.success() : Result.failure();

    }
    /*更新*/
    @PostMapping("/update")
    public Result update(@RequestBody User user) {

        return userService.updateById(user)?Result.success() : Result.failure();

    }
    /**
     * 新增或更新
     * 所做的任何操作必须要获取到id值
     * 不然将会按照Mapper里写的方法执行
     *
     * */
    @PostMapping("/AddOrUpdate")
    public Result AddOrUpdate(@RequestBody User user) {

        return userService.saveOrUpdate(user)?Result.success() : Result.failure();

    }
    /*删除*/
    @PostMapping("/delete")
    public Result delete(Integer id){

        return userService.removeById(id)?Result.success() : Result.failure();

    }
    /*模糊查询*/
    @PostMapping("/Obscure")
    public Result Obscure(@RequestBody User user){

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper();
        if (StringUtils.isNotBlank(user.getOpenid())){
            queryWrapper.like(User ::getOpenid,user.getOpenid());
        }
        return Result.success(userService.list(queryWrapper));

    }

    /*分页*/
/*    @PostMapping("/page/")
    public RespPageEntity getAllUserByPage(@RequestParam(defaultValue = "1") Integer page,
                                           @RequestParam(defaultValue = "20") Integer size,
                                           @RequestParam(defaultValue = "") String realname){

        return userService.getAllUserByPage(page,size,realname);


    }*/

    /**
     * 用户头像上传+登陆表单
     * 这个是作为一个整体直接走
     * 下面的Image方法是分开的
     * 头像是先走后端返回一个值
     * 小程序端先缓存
     * 然后再跟着数据一起走
    */
/*    @ApiOperation(value = "上传文件,form-data当时,传值file",notes = "上传文件,form-data方式,传值file")
    @PostMapping("/uploadFile")
    public JSONObject uploadFile(HttpServletRequest req, HttpServletResponse res){

        JSONObject data = new JSONObject();
        try {
            MultipartHttpServletRequest mreq = (MultipartHttpServletRequest) req;
            MultipartFile file = mreq.getFile("file");
            if (file.getSize() > 0){
                String path = "/CAStudio";
                String fileUrl = COSConfig.uploadFile(file, path,req.getServletContext());
                *//*前端数据获取*//*
                String openid = req.getParameter("openid");
                String dormnum = req.getParameter("dormnum");
                String gender = req.getParameter("gender");
                String nickname = req.getParameter("nickname");
                String phone = req.getParameter("phone");
                String realname = req.getParameter("realname");
                String stunum = req.getParameter("stunum");

                data.put("code",200);
                data.put("msg","上传成功");
                data.put("fileUrl",fileUrl);

                System.out.println(openid);
                System.out.println(fileUrl);
                System.out.println(dormnum);
                System.out.println(gender);
                System.out.println(nickname);
                System.out.println(phone);
                System.out.println(realname);
                System.out.println(stunum);

                userService.updateUser(fileUrl,dormnum,gender,nickname,phone,realname,stunum,openid);

                return data;
            }else {
                data.put("code", 400);
                data.put("msg","请上传文件");
                return data;
            }
        }catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            data.put("code",500);
            data.put("msg", "网络开小差了");
            return data;
        }

    }

    *//**
     * 用户头像先行上传
     * 后端已经把图片上传到服务器，返回一个字符串(data)
     * 然后前端表单数据+返回的data数据
     * 直接调用 UserController AddOrUpdate接口
     * 直接把所有数据get然后根据openid进行数据的更新
     * *//*
    @ApiOperation(value = "上传文件,form-data当时,传值file",notes = "上传文件,form-data方式,传值file")
    @PostMapping("/Image")
    public JSONObject uploadImage(HttpServletRequest req, HttpServletResponse res){

        JSONObject data = new JSONObject();
        try {
            MultipartHttpServletRequest mreq = (MultipartHttpServletRequest) req;
            MultipartFile Image = mreq.getFile("Image");
            if (Image.getSize() > 0){
                String path = "/CAStudio";
                String image = COSConfig.uploadFile(Image, path,req.getServletContext());
                *//*前端数据获取*//*
                //String openid = req.getParameter("openid");
                data.put("code",200);
                data.put("msg","上传成功");
                data.put("image",image);
                *//*System.out.println(image);
                System.out.println(openid);
                userService.saveImage(image,openid);*//*
                System.out.println(data);
                return data;
            }else {
                data.put("code", 400);
                data.put("msg","请上传文件");
                return data;
            }
        }catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            data.put("code",500);
            data.put("msg", "网络开小差了");
            return data;
        }
    }*/

    /**小程序端登陆
     * 用户静态登录
     * 1. 从小程序端获取code
     * 2. 从小程序端获取用户的openid
     * 3. 创建构造函数user从数据库中查找是否有这个openid
     *   (1)有这个openid，则更新时间，静态登录
     *   (2)没有这个openid，则插入新数据，实现静态登录
     * */
    @PostMapping("/getUserInfo")
    public String getUserInfo(@RequestBody Code c){
        System.out.println("输出:"+c.getCode());
        String code = c.getCode();
        if (code == null){
            return ApiResult.args();
        }
        try {
            String openid = userService.getOpenId(code);
            User user = userMapper.getUserInfo(openid);
            if (user == null) {
                String time = TimeUtils.getNowDateTime();
                userMapper.insertUserInfo(time,openid);
                User user_1=new User();
                user_1.setOpenid(openid);
                return ApiResult.ok(user_1);
            }else {
                String time = TimeUtils.getNowDateTime();
                userMapper.updateLogin(openid,time);
                return ApiResult.ok(user);
            }
        }catch (Exception e) {
            log.error(e.toString());
            return ApiResult.error();
        }
    }

    /**
     * 分页
     * 利用mybatis-plus原生方法
     */
    @GetMapping("/{currentPage}/{PageSize}")
    public R getPage(@PathVariable Integer currentPage,@PathVariable Integer PageSize,User user){
        IPage<User> page = userService.getPage(currentPage,PageSize,user );
        //如果当前页码之大于总页码值，重新执行查询操作，使用最大页码作为当前页码值
        if (currentPage > page.getPages())//如果当前页码之大于总页码值
            page = userService.getPage((int)page.getPages(),PageSize);//使用最大页码作为当前页码值
        return new R(true,page);
    }
}
